package com.esdk.sql;

import com.esdk.sql.orm.AbstractSelect;
import com.esdk.utils.EasyReflect;
import com.esdk.utils.EasyStr;

public class JoinConfig {
	public static final String INNERJOIN=Table.INNERJOIN,LEFTJOIN=Table.LEFTJOIN,RIGHTJOIN=Table.RIGHTJOIN,FULLJOIN=Table.FULLJOIN;
	public static final String PRIMARY_KEY="PrimaryKey";

	public JoinConfig on(AbstractSelect majorSelect,AbstractSelect primaryKeySelect,String joinType) {
		on(majorSelect,primaryKeySelect);
		primaryKeySelect.getTable().setRelationShip(joinType);
		return this;
	}

	public JoinConfig on(AbstractSelect majorSelect,AbstractSelect joinSelect) {
		String primaryKeyName=(String)EasyReflect.getFieldValue(joinSelect.getMetaData(),PRIMARY_KEY);
		String foreignKeyName=(String)EasyReflect.getFieldValue(majorSelect.getMetaData(),EasyStr.toCamelCase(primaryKeyName,true));
		joinSelect.addOnCondition(majorSelect.createField(foreignKeyName),joinSelect.createField(primaryKeyName));
		return this;
	}

	private String findOnPrimaryKeyName(AbstractSelect select1,AbstractSelect select2){
		String pkname2=(String)EasyReflect.getFieldValue(select2.getMetaData(),"PrimaryKey");
		java.lang.reflect.Field field1=EasyReflect.findField(select1.getMetaData().getClass(),EasyStr.toCamelCase(pkname2,true),false);
		if(field1!=null){
			return pkname2;
		}
		String pkname1=(String)EasyReflect.getFieldValue(select1.getMetaData(),"PrimaryKey");
		java.lang.reflect.Field field2=EasyReflect.findField(select2.getMetaData().getClass(),EasyStr.toCamelCase(pkname1,true),false);
		if(field2!=null){
			return pkname1;
		}
		return null;
	}

	public JoinConfig onPrimaryKey(AbstractSelect majorSelect,AbstractSelect joinSelect) {
		String primaryKeyName=findOnPrimaryKeyName(majorSelect,joinSelect);
		if(primaryKeyName!=null){
			joinSelect.addOnCondition(joinSelect.createField(primaryKeyName),majorSelect.createField(primaryKeyName));
		}
		return this;
	}
	
	public JoinConfig on(Select joinSelect,ILogic logic) {
		joinSelect.addOnCondition(logic);
		return this;
	}
	
	public JoinConfig on(Select joinSelect,ILogic logic,String joinType) {
		joinSelect.addOnCondition(logic);
		joinSelect.getTable().setRelationShip(joinType);
		return this;
	}
	
	public JoinConfig on(Select joinSelect,Field f1,Field f2) {
		joinSelect.addOnCondition(f1,f2);
		return this;
	}

	public JoinConfig on(Select joinSelect,Field f1,Field f2,String joinType) {
		joinSelect.addOnCondition(f1,f2);
		joinSelect.getTable().setRelationShip(joinType);
		return this;
	}
	
	public JoinConfig on(AbstractSelect joinSelect,Field f1,Field f2) {
		joinSelect.addOnCondition(f1,f2);
		return this;
	}
	
	public JoinConfig on(AbstractSelect joinSelect,Field f1,Field f2,String joinType) {
		joinSelect.addOnCondition(f1,f2);
		joinSelect.getTable().setRelationShip(joinType);
		return this;
	}
}
